package auth

import (
	"github.com/gin-gonic/gin"
	logic2 "iot-base/auth/api/logic"
	"iot-base/auth/logger"
	types2 "iot-base/auth/types"
)

type DeleteRule struct {
	Id int64 `json:"id"`
}

type RulePage struct {
	Page int `json:"page"`
	Size int `json:"size"`
	Type int `json:"type"`
}

// AddRule 添加权限规则.
func AddRule(c *gin.Context) {
	requestId, _ := c.Get("RequestId")
	resp := types2.NewResult(c)
	var rule types2.ReqAuthRule
	err := c.ShouldBind(&rule)
	if err != nil {
		resp.ErrorCode(types2.ParamsError, err.Error())
		return
	}
	logic := logic2.NewRulesLogic()
	err = logic.AddRule(rule)
	if err != nil {
		logger.Log.Errorf("[%v] err:=[%v]", requestId, err)
		resp.ErrorCode(types2.ExceptionError, err.Error())
	}
	resp.Success(gin.H{})
}

// DelRule 删除角色.
func DelRule(c *gin.Context) {

	requestId, _ := c.Get("RequestId")
	resp := types2.NewResult(c)
	var delRule DeleteRule
	err := c.ShouldBind(&delRule)
	if err != nil || delRule.Id == 0 {
		resp.ErrorCode(types2.ParamsError, err.Error())
		return
	}

	rulesLogic := logic2.NewRulesLogic()
	err = rulesLogic.DelRule(delRule.Id)
	if err != nil {
		logger.Log.Errorf("[%v] err:=[%v]", requestId, err)
		resp.ErrorCode(types2.ExceptionError, err.Error())
	}
	resp.Success(gin.H{})
}

// EditRule 修改角色.
func EditRule(c *gin.Context) {
	requestId, _ := c.Get("RequestId")
	resp := types2.NewResult(c)
	var rule types2.ReqAuthRule
	err := c.ShouldBind(&rule)
	if err != nil || rule.Id == 0 {
		resp.ErrorCode(types2.ParamsError, "")
		return
	}
	logic := logic2.NewRulesLogic()
	err = logic.EditRule(rule)
	if err != nil {
		logger.Log.Errorf("[%v] err:=[%v]", requestId, err)
		resp.ErrorCode(types2.ExceptionError, "")
		return
	}
	resp.Success(gin.H{})
}

func FindRule(c *gin.Context) {
	resp := types2.NewResult(c)
	logic := logic2.NewRulesLogic()
	ret, err := logic.FindRuleAll()
	if err != nil {
		resp.ErrorCode(types2.DBError, err.Error())
		return
	}
	resp.Success(gin.H{"list": ret})
}

func Menu(c *gin.Context) {
	uid, _ := c.Get("uid")
	resp := types2.NewResult(c)
	logic := logic2.NewRulesLogic()
	var req types2.ReqMenu
	err := c.ShouldBind(&req)
	if err != nil {
		resp.ErrorCode(types2.ParamsError, "")
		return
	}
	ret, err := logic.FindMenu(uid.(int64), req.GroupId, 0)
	if err != nil {
		resp.ErrorCode(types2.DBError, err.Error())
		return
	}
	resp.Success(gin.H{"list": ret})
}

func GroupMenu(c *gin.Context) {
	uid := c.GetInt64("uid")
	resp := types2.NewResult(c)
	logic := logic2.NewRulesLogic()
	ret, err := logic.FindGroupMenu(uid)
	if err != nil {
		resp.ErrorCode(types2.DBError, err.Error())
		return
	}
	resp.Success(ret)
}
